package com.hyzh.latte.vehicle.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import io.minio.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Base64;
import java.util.Date;

/**
 * @author songkui
 * @since 2024/7/5 14:13
 */
@Service
@Slf4j
@AllArgsConstructor
public class MinioService {
    private final MinioClient minioClient;
    private final  static  String BUCKET = "latte";

    public String putInoutImage(String park, String base64)throws Exception {
        if (StrUtil.isEmpty(base64)){
            return null;
        }

        String base64String = base64
                .replace("data:image/png;base64,", "")
                .replace("data:image/jpeg;base64,", "")
                .replace("data:image/jpg;base64,", "")
                .replace(" ", "+");
        byte[] imageBytes = Base64.getMimeDecoder().decode(base64String);
        InputStream inputStream = new ByteArrayInputStream(imageBytes);

        boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(BUCKET).build());
        if (!isExist) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(BUCKET).build());
        }

        String objectName = buildImportObject();
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(BUCKET)
                .object(objectName)
                .stream(inputStream, inputStream.available(), -1)
                .build());

        return objectName;
    }

    public  String buildImportObject(){
        String date = DateUtil.formatDate(new Date());
        return String.format( "vehicle/%s/%s%s", date, "INOUT_EN_"+ RandomUtil.randomString(16), ".jpg");
    }



}
